package org.LowAltitudeEconomy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.LowAltitudeEconomy.service.UserService;
import org.LowAltitudeEconomy.Utils.Md5Util;
import org.LowAltitudeEconomy.mapper.UserMapper;
import org.LowAltitudeEconomy.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //用户注册
    @Override
    public void register(String username, String password, String phone, String full_name) {
        User user = new User();
        user.setUserName(username);
        user.setPassword(Md5Util.getMD5String(password));
        user.setPhone(phone);
        user.setFullName(full_name);
        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            System.out.println("用户已存在");
        }
    }

    //匹配名字（为其他功能做铺垫）
    @Override
    public User findUserByUsername(String username) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));
        if (user == null) {
            return null;
        } else {
            return user;
        }
    }


    //用户登录
    @Override
    public User login(String username, String password) {
        User user = findUserByUsername(username);
        if (user == null) {
            return null;
        } else {
            if (user.getPassword().equals(Md5Util.getMD5String(password))) {
                return user;
            } else {
                return null;
            }
        }
    }
}

